//
//  PictureSelectorViewController.swift
//  sina
//
//  Created by DXapple on 15/11/22.
//  Copyright © 2015年 sqlite. All rights reserved.
//

import UIKit
private let maxImageCount = 3

private let reuseIdentifier = "Cell"
private let column: CGFloat = 4
private let pictureCellMaigin: CGFloat = 10
class PictureSelectorViewController: UICollectionViewController {
    private lazy var
    imageList = [UIImage]()
    init() {
    let layout = UICollectionViewFlowLayout()
        let w = (screenW - (column + 1) * pictureCellMaigin) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = pictureCellMaigin
        layout.minimumLineSpacing = pictureCellMaigin
        //设置section间距
        layout.sectionInset = UIEdgeInsets(top: pictureCellMaigin, left: pictureCellMaigin, bottom: 0, right: pictureCellMaigin)
        
        
        super.init(collectionViewLayout: layout)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

    
        self.collectionView!.registerClass(pictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

   

    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = (imageList.count == maxImageCount) ? 0 : 1
        
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! pictureSelectorCell
    cell.backgroundColor = UIColor.randomColor()
        cell.selectorCellDelegate = self
        if indexPath.item == imageList.count{

            cell.image = nil

        } else {
        
            cell.image = imageList[indexPath.item]
        }
        return cell
    }
}
extension PictureSelectorViewController:PictureSelectorCellDelegate{
    func userWillAddPictrue(cell: pictureSelectorCell) {
        if cell.image != nil{
        
        print("yijing添加图片")
        return}
        //使用系统图片选择器
        let picker = UIImagePickerController()
        //指定代理
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
        
    }
    func userWilleDeletePicture(cell: pictureSelectorCell) {
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        cell.alpha = 1
        self.collectionView?.reloadData()
    }


    
}

extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        print(image)
        print(editingInfo)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }

    
}

@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {

//定义协议方法  添加图片的协议方法
    optional func userWillAddPictrue(cell: pictureSelectorCell)
    optional func userWilleDeletePicture(cell: pictureSelectorCell)
    
}



class  pictureSelectorCell: UICollectionViewCell {
    weak var  selectorCellDelegate: PictureSelectorCellDelegate?
    
    
    @objc private func addBtnDidClick() {
        
        selectorCellDelegate?.userWillAddPictrue?(self)
        
    
    }
    @objc private func deleteBtnDidClick() {
        selectorCellDelegate?.userWilleDeletePicture?(self)

    }
    var image: UIImage? {
        didSet{
            deleteBtn.hidden = (image == nil)
            if  image != nil {
                addBtn.setBackgroundImage(image
                    , forState: .Normal)
            } else {
            
            addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.top.equalTo(contentView)
        }
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
        
        
    
    }
    
    
    private lazy var
    addBtn: UIButton = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    private lazy var
    deleteBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)
    
    
}





